import { Component } from '@tarojs/taro'
import lodash from "@/utils/lodash"
import { calcSurplusTime } from "@/utils/utils"

export default class FyComponent<P = {}, S = {}> extends Component<P, S> {
  props: any
  timer: any
  seconds: number
  timeout: number
  prevProps: any

  constructor() {
    super(...arguments)
    this.timeout = 50
  }

  componentDidMount() {
    this.prevProps = lodash.cloneDeep(this.props)
    this.setTimer(this.prevProps.seconds)
  }

  componentWillReceiveProps(nextProps: any) {
    // console.log('倒计时：componentWillReceiveProps')
    if (JSON.stringify(this.prevProps) === JSON.stringify(nextProps)) return
    // console.log('倒计时：------------ componentWillReceiveProps ------------')
    this.prevProps = lodash.cloneDeep(nextProps)
    this.clearTimer()
    this.setTimer(nextProps.seconds)
  }

  //  在一个组件被 卸载(unmounted) 和 销毁(destroyed) 之前立即被调用
  componentWillUnmount() {
    this.clearTimer()
  }

  /**
   * 开启倒计时
   */
  setTimer(seconds) {
    this.seconds = seconds
    if (!this.timer) this.countdown()
  }

  /**
   * 清除计时器
   */
  clearTimer() {
    if (this.timer) {
      clearTimeout(this.timer as number)
      this.timer = undefined
    }
  }

  /**
   * 倒计时
   */
  countdown() {
    if (this.seconds === undefined) {
      return;
    }

    const timeout = lodash.cloneDeep(this.timeout)
    let s = 1000 - timeout
    this.timer = setInterval(() => {
      if (s >= 1000 - timeout) {
        s = 0
        this.seconds--
      } else {
        s += timeout
      }

      const time:any = calcSurplusTime(this.seconds)
      time.millisecond = Math.floor(s / 10)
      this.onIntervalCallBack(time)

      if (this.seconds < 0) {
        this.clearTimer()
        this.props.onTimeUp && this.props.onTimeUp()
      }
    }, this.timeout)
  }

  //  格式化时间数字
  formatNum(num) {
    return (num < 10 ? `0${num}` : `${num}`)
  }

  //  回调
  onIntervalCallBack(time) {
    console.log(time)
  }
}
